<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="mb-8">
      <el-col v-for="(card, index) in statCards" :key="index" :xs="24" :sm="12" :md="6">
        <div class="stat-card" :class="card.color">
          <div class="content">
            <div class="num">{{ card.value }}</div>
            <div class="label">{{ card.label }}</div>
          </div>
          <div class="icon">
            <i :class="card.icon"></i>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要数据区域 -->
    <el-row :gutter="20">
      <!-- 环境数据图表 -->
      <el-col :xs="24" :lg="16">
        <div class="chart-card">
          <div class="header">
            <h3>环境数据趋势</h3>
            <el-select v-model="chartDays" size="small" style="width: 120px">
              <el-option label="最近7天" value="7" />
              <el-option label="最近30天" value="30" />
            </el-select>
          </div>
          <div ref="chart" style="height: 400px;"></div>
        </div>
      </el-col>

      <!-- 报警信息 -->
      <el-col :xs="24" :lg="8">
        <div class="alert-card">
          <h3>实时报警（{{ recentAlerts.length }}条）</h3>
          <el-scrollbar height="400px">
            <div v-for="(alert, index) in recentAlerts" :key="index" class="alert-item">
              <div class="alert-time">{{ formatTime(alert.warningTime) }}</div>
              <div class="alert-message">
                <el-tag type="danger" size="small">报警</el-tag>
                {{ alert.warningMessage }}
              </div>
              <div class="alert-device">设备ID：{{ alert.deviceId }}</div>
            </div>
            <el-empty v-if="recentAlerts.length === 0" description="暂无报警" />
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import * as echarts from 'echarts'

import { listFamilies } from "@/api/airsystem/families";
import {listDevices} from "@/api/airsystem/devices";

import {listWarnings,} from "@/api/airsystem/warnings";
import { listTemp, } from "@/api/airsystem/temp";
const chart = ref(null)
let myChart = null

// 数据状态
const devices = ref([])
const warnings = ref([])
const families = ref([])
const tempData = ref([])
const chartDays = ref('7')

// 获取数据
const fetchData = async () => {
  try {
    const [devRes, warnRes, famRes, tempRes] = await Promise.all([
      listDevices({ pageSize: 1000 }),
      listWarnings({ pageSize: 10 }),
      listFamilies({ pageSize: 1000 }),
      listTemp({ pageSize: 100 })
    ])

    devices.value = devRes.rows || []
    warnings.value = warnRes.rows || []
    families.value = famRes.rows || []
    tempData.value = tempRes.rows || []

    initChart()
  } catch (error) {
    console.error('数据加载失败:', error)
  }
}

// 统计卡片数据
const statCards = computed(() => [
  {
    label: '总设备数',
    value: devices.value.length,
    color: 'blue',
    icon: 'el-icon-cpu'
  },
  {
    label: '在线设备',
    value: devices.value.filter(d => d.status === 'online').length,
    color: 'green',
    icon: 'el-icon-success'
  },
  {
    label: '报警数量',
    value: warnings.value.length,
    color: 'red',
    icon: 'el-icon-warning'
  },
  {
    label: '家庭数量',
    value: families.value.length,
    color: 'purple',
    icon: 'el-icon-house'
  }
])

// 近期报警
const recentAlerts = computed(() =>
    warnings.value.slice(0, 5).map(alert => ({
      ...alert,
      device: devices.value.find(d => d.deviceId === alert.deviceId) || {}
    }))
)

// 图表初始化
const initChart = () => {
  if (!myChart) {
    myChart = echarts.init(chart.value)
  }

  const days = parseInt(chartDays.value)
  const chartData = {
    date: [],
    temperature: [],
    humidity: []
  }

  tempData.value.slice(-days).forEach(item => {
    chartData.date.push(item.recordTime)
    chartData.temperature.push(item.temperature)
    chartData.humidity.push(item.humidity)
  })

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['温度', '湿度'] },
    xAxis: {
      type: 'category',
      data: chartData.date,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '温度',
        type: 'line',
        data: chartData.temperature,
        smooth: true,
        lineStyle: { color: '#409EFF' },
        areaStyle: { color: 'rgba(64, 158, 255, 0.1)' }
      },
      {
        name: '湿度',
        type: 'line',
        data: chartData.humidity,
        smooth: true,
        lineStyle: { color: '#67C23A' },
        areaStyle: { color: 'rgba(103, 194, 58, 0.1)' }
      }
    ]
  }

  myChart.setOption(option)
}

// 时间格式化
const formatTime = (time) => {
  return new Date(time).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchData()
  setInterval(fetchData, 30000) // 30秒刷新数据
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .stat-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    color: white;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-3px);
    }

    .content {
      .num {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .label {
        font-size: 14px;
        opacity: 0.9;
      }
    }

    .icon {
      font-size: 40px;
      opacity: 0.2;
    }

    &.blue { background: linear-gradient(45deg, #409EFF, #79BBFF); }
    &.green { background: linear-gradient(45deg, #67C23A, #95D475); }
    &.red { background: linear-gradient(45deg, #F56C6C, #F89898); }
    &.purple { background: linear-gradient(45deg, #909399, #B1B3B8); }
  }

  .chart-card, .alert-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    margin-bottom: 20px;

    h3 {
      margin: 0 0 20px 0;
      font-size: 16px;
      color: #303133;
    }
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .alert-item {
    padding: 12px 0;
    border-bottom: 1px solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .alert-time {
      font-size: 12px;
      color: #909399;
      margin-bottom: 4px;
    }

    .alert-message {
      margin: 6px 0;
      color: #606266;
    }

    .alert-device {
      font-size: 12px;
      color: #409EFF;
    }
  }
}
</style>